package com.android.systemui.statusbar.board;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.RemoteException;
import android.os.DisplayOutputManager;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.android.systemui.R;
import com.android.systemui.language.LanguageAdapter;
import com.android.systemui.language.LanguageUtils;

import java.util.Locale;

/**
 * Created by bruce on 17-12-18.
 */
class MoreSettingsDialog extends BaseDialog {

    private static final String TAG = "MoreSettingsDialog";
    private static final String TOUCH_DELAY = "touch_delay";

    private static final int MAX_SCALE = 100;
    private static final int MIN_SCALE = 80;

    private SharedPreferences boardSp;
    private int touchDelay = 0;

    private AudioManager am;
    private int maxVolume;    //获取系统最大音量
    private int currentVolume;    //获取当前音量
    private int currentBrightness;

    private DisplayOutputManager mDisplayOutputManager = null;
    private int mDisplayer;

    Intent intentSensitivity;

    MoreSettingsDialog(Context context) {
        super(context);
        am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        initBoardSp();

        try {
            mDisplayOutputManager = new DisplayOutputManager();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        if (mDisplayOutputManager.getDisplayNumber() == 2)
            mDisplayer = mDisplayOutputManager.AUX_DISPLAY;
        else
            mDisplayer = mDisplayOutputManager.MAIN_DISPLAY;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.pop_settings_more;
    }

    @Override
    protected void initView(View view) {
        initScreenOrient(view);
        initVolume(view);
        initBrightness(view);
        initSensitivity(view);
        initScreenScale(view);
        initEyeProtection(view);
        initLanguage(view);
    }

    private void initScreenOrient(View view) {
        RadioGroup rgScreenOrient = (RadioGroup) view.findViewById(R.id.rg_screen_orient);
        switch (BoardUtil.getScreenRotation(mContext)) {
            case 3:
                ((RadioButton) view.findViewById(R.id.rb_vertical)).setChecked(true);
                break;
            case 0:
                ((RadioButton) view.findViewById(R.id.rb_horizontal)).setChecked(true);
                break;
            case 1:
                ((RadioButton) view.findViewById(R.id.rb_vertical_inverse)).setChecked(true);
                break;
            case 2:
                ((RadioButton) view.findViewById(R.id.rb_horizontal_inverse)).setChecked(true);
                break;
            default:
        }
        rgScreenOrient.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Intent orientationChangeIntent = new Intent("com.w2here.board.settings");
                BoardUtil.disableAccelerometerRotation(mContext);
                int orientation = 0;
                switch (checkedId) {
                    case R.id.rb_horizontal:
                        orientation = 0;
                        break;
                    case R.id.rb_vertical:
                        orientation = 3;
                        break;
                    case R.id.rb_horizontal_inverse:
                        orientation = 2;
                        break;
                    case R.id.rb_vertical_inverse:
                        orientation = 1;
                        break;
                    default:
                }

                orientationChangeIntent.putExtra("orientation", orientation);
                mContext.sendBroadcast(orientationChangeIntent);

                BoardUtil.setScreenRotation(mContext, orientation);

            }
        });
    }

    private void initVolume(View view) {
        SeekBar sbVolume = (SeekBar) view.findViewById(R.id.sb_volume);
        sbVolume.setMax(maxVolume);
        sbVolume.setProgress(currentVolume);
        sbVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    //设置系统音量
                    am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                    currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                    seekBar.setProgress(currentVolume);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    private void initEyeProtection(View view) {
        ToggleButton tbEyeProtection = (ToggleButton) view.findViewById(R.id.tb_eye_protection);
        tbEyeProtection.setChecked(mContext.getSharedPreferences(mContext.getPackageName(), 0)
                .getBoolean("EYE_PROTECTION", false));
        tbEyeProtection.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                ScreenFilterService.setEyeProtectionMode(b);
                saveEyeProtectionMode(b);
            }
        });
    }

    private void initBrightness(View view) {
        SeekBar sbBrightness = (SeekBar) view.findViewById(R.id.sb_brightness);
        Log.e(TAG, "888888 BRIGHTNESS MODE = " + BoardUtil.getScreenMode(mContext));
        BoardUtil.setScreenMode(mContext, 0);
        sbBrightness.setMax(80);
        sbBrightness.setProgress((int) mContext.getSharedPreferences(mContext.getPackageName(), 0)
                .getFloat("SCREEN_BRIGHTNESS", 80f));
        sbBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    ScreenFilterService.updateScreenFilter(progress);
                    seekBar.setProgress(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                saveCurrentSettings(seekBar.getProgress());
            }
        });
    }

    void initSensitivity(View view) {
        SeekBar sbSensitivity = (SeekBar) view.findViewById(R.id.sb_sensitivity);
        BoardUtil.setScreenMode(mContext, 0);
        sbSensitivity.setMax(100);
        sbSensitivity.setProgress(touchDelay >= 20 ? touchDelay - 20 : 0);
        sbSensitivity.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (intentSensitivity == null)
                    intentSensitivity = new Intent("com.w2here.board.TOUCH_DELAY");
                touchDelay = seekBar.getProgress() + 20;
                Log.e(TAG, "888888 touchDelay = " + touchDelay);
                intentSensitivity.putExtra(TOUCH_DELAY, touchDelay);
                mContext.sendBroadcast(intentSensitivity);
//                boardSp.edit().putInt(TOUCH_DELAY, touchDelay).apply();
            }
        });
    }

    private void initBoardSp() {
        try {
            Context boardContext = mContext.createPackageContext(
                    "com.w2here.board", Context.CONTEXT_IGNORE_SECURITY);
            boardSp = boardContext.getSharedPreferences("hhapp_base_cache",
                    Context.MODE_MULTI_PROCESS);
            touchDelay = boardSp.getInt(TOUCH_DELAY, 120);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void initScreenScale(View view) {
        view.findViewById(R.id.iv_vertical_reduce).setOnClickListener(mOnClick);
        view.findViewById(R.id.iv_vertical_add).setOnClickListener(mOnClick);
        view.findViewById(R.id.iv_horizontal_reduce).setOnClickListener(mOnClick);
        view.findViewById(R.id.iv_horizontal_add).setOnClickListener(mOnClick);
        view.findViewById(R.id.iv_default).setOnClickListener(mOnClick);
    }

    private void initLanguage(View view) {
        Locale locale = LanguageUtils.getCurrentLaungage(mContext);
        String currentLanguage = LanguageUtils.loacalToString(locale);
        ((TextView)(view.findViewById(R.id.tv_language))).setText(currentLanguage);

        view.findViewById(R.id.rl_language).setOnClickListener(mOnClick);
    }

    private View.OnClickListener mOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            if (mDisplayOutputManager == null) return;
            int scaleValue;
            switch (v.getId()) {
                case R.id.iv_horizontal_add:
                    scaleValue = mDisplayOutputManager.getOverScan(mDisplayer).right + 1;
                    setOverScan(scaleValue, mDisplayOutputManager.DISPLAY_OVERSCAN_X);
                    break;
                case R.id.iv_horizontal_reduce:
                    scaleValue = mDisplayOutputManager.getOverScan(mDisplayer).left - 1;
                    setOverScan(scaleValue, mDisplayOutputManager.DISPLAY_OVERSCAN_X);
                    break;
                case R.id.iv_vertical_reduce:
                    Log.e(TAG, "888888 iv_vertical_reduce");
                    scaleValue = mDisplayOutputManager.getOverScan(mDisplayer).top - 1;
                    setOverScan(scaleValue, mDisplayOutputManager.DISPLAY_OVERSCAN_Y);
                    break;
                case R.id.iv_vertical_add:
                    Log.e(TAG, "888888 iv_vertical_add");
                    scaleValue = mDisplayOutputManager.getOverScan(mDisplayer).bottom + 1;
                    setOverScan(scaleValue, mDisplayOutputManager.DISPLAY_OVERSCAN_Y);
                    break;
                case R.id.iv_default:
                    setDefaultOverScan();
                    break;
                case R.id.rl_language:
                    jumpToLanguageSetting();
                    break;
            }
        }
    };

    private void setOverScan(int scaleValue, int orientation) {
        if (scaleValue < MIN_SCALE) scaleValue = MIN_SCALE;
        else if (scaleValue > MAX_SCALE) scaleValue = MAX_SCALE;

        if (scaleValue >= 0)
            mDisplayOutputManager.setOverScan(mDisplayer, orientation, scaleValue);
    }

    private void setDefaultOverScan() {
        mDisplayOutputManager.setOverScan(mDisplayer, mDisplayOutputManager.DISPLAY_OVERSCAN_X, MAX_SCALE);
        mDisplayOutputManager.setOverScan(mDisplayer, mDisplayOutputManager.DISPLAY_OVERSCAN_Y, MAX_SCALE);
    }

    private void jumpToLanguageSetting() {
        final View languageSettingView =  baseView.findViewById(R.id.ll_language_setting);

        ListView listView = (ListView) languageSettingView.findViewById(R.id.lv_language);
        listView.setAdapter(new LanguageAdapter(mContext));

        languageSettingView.setVisibility(View.VISIBLE);
        baseView.findViewById(R.id.fl_setting).setVisibility(View.INVISIBLE);

        languageSettingView.findViewById(R.id.ll_language_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                languageSettingView.setVisibility(View.GONE);
                baseView.findViewById(R.id.fl_setting).setVisibility(View.VISIBLE);
            }
        });
    }

    private void saveCurrentSettings(float brightness) {
        SharedPreferences sp = mContext.getSharedPreferences(mContext.getPackageName(), 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.putFloat("SCREEN_BRIGHTNESS", brightness);
        editor.apply();
    }

    private void saveEyeProtectionMode(boolean mode) {
        SharedPreferences sp = mContext.getSharedPreferences(mContext.getPackageName(), 0);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("EYE_PROTECTION", mode);
        editor.apply();
    }

}
